﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace OpenGL
{
    static public partial class GL
    {
        private const string
         KER_DLL = "kernel32.dll",
         OGL_DLL = "opengl32.dll",
         GLU_DLL = "glu32.dll",
         GDI_DLL = "gdi32.dll",
         USR_DLL = "user32.dll";

        // kernel32.dll 
        [DllImport(KER_DLL)]
        private static extern uint LoadLibrary(string lpFileName);

        //opengl32.dll
        [DllImport(OGL_DLL)]
        internal static extern uint wglGetCurrentContext();
        [DllImport(OGL_DLL)]
        internal static extern IntPtr wglCreateContext(IntPtr hdc);
        [DllImport(OGL_DLL)]
        internal static extern int wglMakeCurrent(IntPtr hdc, IntPtr hglrc);
        [DllImport(OGL_DLL)]
        internal static extern int wglDeleteContext(IntPtr hglrc);
        [DllImport(OGL_DLL)]
        internal static extern IntPtr wglGetProcAddress(string name);

        // gdi32.dll
        [DllImport(GDI_DLL)]
        internal unsafe static extern int ChoosePixelFormat(IntPtr hdc, PixelFormatDescriptor* ppfd);
        [DllImport(GDI_DLL)]
        internal unsafe static extern int SetPixelFormat(IntPtr hdc, int iPixelFormat, PixelFormatDescriptor* ppfd);
        [DllImport(GDI_DLL)]
        internal static extern int SwapBuffers(IntPtr hdc);

        // user32.dll
        [DllImport(USR_DLL)]
        internal static extern IntPtr GetDC(IntPtr hWnd);
        [DllImport(USR_DLL)]
        internal static extern int RelaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport(USR_DLL)]
        internal static extern IntPtr SetCapture(IntPtr hWnd);
        [DllImport(USR_DLL)]
        internal static extern int ReleaseCapture();

        static GL()
        {
            var result = GL.LoadLibrary(OGL_DLL);
            if (result == 0)
            {
                throw new InvalidOperationException(OGL_DLL);
            }
            result = GL.LoadLibrary(GLU_DLL);
            if (result == 0)
            {
                throw new InvalidOperationException(GLU_DLL);
            }
            result = GL.LoadLibrary(GDI_DLL);
            if (result == 0)
            {
                throw new InvalidOperationException(GDI_DLL);
            }
            result = GL.LoadLibrary(USR_DLL);
            if (result == 0)
            {
                throw new InvalidOperationException(USR_DLL);
            }
        }
    }
}
